﻿#if UNITY_EDITOR
#endif

using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace QFramework
{
    [CreateAssetMenu(menuName = "@ItemKit/Create Item Language Package")]
    public class ItemLanguagePackage : ScriptableObject
    {
        [DisplayLabel("物品数据库")]
        public ItemDatabase ItemDatabase;
        [DisplayLabel("语言")]
        public string Lanuage;
        [Header("本地化物品")]
        public List<LocalItem> LocalItems = new();

        #region subclass
        [Serializable]
        public class LocalItem
        {
            public string Key;
            [DisplayLabel("名字")]
            public string Name;
            [DisplayLabel("描述")]
            public string Description;
        }
        #endregion

        private void OnValidate()
        {
            if (ItemDatabase && LocalItems.Count == 0)
            {
                foreach (var item in ItemDatabase.Items)
                {
                    LocalItems.Add(new LocalItem()
                    {
                        Key = item.Key,
                        Name = item.Name,
                        Description = item.Description,
                    });
                }
            }
            else if (ItemDatabase && LocalItems.Count != 0)
            {
                LocalItems.RemoveAll(item => ItemDatabase.Items.All(i => i.GetKey != item.Key));

                var newLocalItems = new List<LocalItem>();
                foreach (var item in ItemDatabase.Items)
                {
                    var localItem2Add = LocalItems.FirstOrDefault(localItem => localItem.Key == item.GetKey);
                    if (localItem2Add != null)
                    {
                        newLocalItems.Add(localItem2Add);
                    }
                    else
                    {
                        newLocalItems.Add(new LocalItem()
                        {
                            Key = item.Key,
                            Name = item.Name,
                            Description = item.Description,
                        });
                    }
                }
                LocalItems = newLocalItems;
            }
            else if (ItemDatabase == null)
            {
                LocalItems.Clear();
            }
        }
    }
}
